using System;
using System.Security.Principal;
using AndyPike.Commons.Extensions;
using AndyPike.Snowflake.Core.Exceptions;
using AndyPike.Snowflake.Core.Services;
using Castle.MonoRail.Framework;

namespace AndyPike.Snowflake.Web.Filters
{
    public class LoadPrincipleFilter : IFilter
    {
        private readonly IAccountService accountService;

        public LoadPrincipleFilter(IAccountService accountService)
        {
            this.accountService = accountService;
        }

        public bool Perform(ExecuteWhen exec, IEngineContext context, IController controller, IControllerContext controllerContext)
        {
            context.CurrentUser = null;
            controllerContext.PropertyBag["currentUser"] = null;
                      
            string authenticationToken = context.Request.ReadCookie("authenticationToken");

            if (authenticationToken.IsGuid())
            {
                try
                {
                    IPrincipal principal = accountService.RetrievePrincipleFromAuthenticationToken(new Guid(authenticationToken));

                    context.CurrentUser = principal;
                    controllerContext.PropertyBag["currentUser"] = principal;
                }
                catch (InvalidAuthenticationTokenException)
                {
                    context.CurrentUser = null;
                    controllerContext.PropertyBag["currentUser"] = null;
                }
            }

            return true;
        }
    }
}